﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.EntityFrameworkCore;
using ERP.ERPModels.EquipmentManage;
using Microsoft.EntityFrameworkCore;

namespace ERP.Web.Controllers
{
    public class PendingtasksController : Controller
    {
        private readonly ERPDbContext _dbContext;
        public PendingtasksController(ERPDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> GetPendingTasks(string documentCode, string materialName, string DocumentsType, int page = 1, int pageSize = 5)
        {
            try
            {
                // 筛选数据
                var query = _dbContext.Set<Pendingtasks>().AsQueryable();

                // 调试输出
                Console.WriteLine($"查询参数: documentCode={documentCode}, materialName={materialName}, DocumentsType={DocumentsType}, page={page}, pageSize={pageSize}");

                if (!string.IsNullOrWhiteSpace(documentCode))
                {
                    query = query.Where(x => x.DocumentsCode.Contains(documentCode));
                }

                if (!string.IsNullOrWhiteSpace(materialName))
                {
                    query = query.Where(x => x.MaterialName.Contains(materialName));
                }

                if (!string.IsNullOrWhiteSpace(DocumentsType))
                {
                    query = query.Where(x => x.DocumentsType.Contains(DocumentsType));
                }


                // 计算总记录数和总页数
                var totalCount = await query.CountAsync();
                var pageCount = (int)Math.Ceiling(totalCount / (double)pageSize);

                // 分页
                var items = await query
                    .OrderByDescending(x => x.Id)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                // 转换为前端需要的格式
                var result = items.Select(item => new
                {
                    id = item.Id, // 使用数字类型的ID
                    documentsCode = item.DocumentsCode,
                    documentsType = item.DocumentsType,
                    materialCode = item.MaterialCode,
                    materialName = item.MaterialName,
                    pendingtasksNum = item.PendingtasksNum,
                    passesNum = item.PassesNum,
                    noPassesNum = item.NoPassesNum,
                    workstationCode = item.WorkstationCode,
                    ticketsCode = item.TicketsCode
                }).ToList();
                
                // 调试输出每条记录的待检数量
                foreach (var item in items)
                {
                    Console.WriteLine($"记录ID={item.Id}, PendingtasksNum={item.PendingtasksNum}, PassesNum={item.PassesNum}, NoPassesNum={item.NoPassesNum}");
                }

                // 调试输出
                Console.WriteLine($"查询结果: 总数={totalCount}, 当前页={page}, 每页大小={pageSize}, 结果数量={result.Count}");

                // 返回分页结果
                return Json(new
                {
                    success = true,
                    data = result,
                    totalCount = totalCount,
                    count = totalCount, // 添加count字段以匹配前端
                    pageCount = pageCount,
                    currentPage = page
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    message = "获取待检任务失败：" + ex.Message
                });
            }
        }

        public async Task<IActionResult> Inspect(int id)
        {
            var task = await _dbContext.Set<Pendingtasks>().FindAsync(id);
            if (task == null)
            {
                return RedirectToAction("Index");
            }

            ViewBag.Task = task;
            return View();
        }

        /// <summary>
        /// 保存检验结果
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> SaveInspection([FromBody] Pendingtasks model)
        {
            try
            {
                // 检查必填字段
                if (model == null)
                {
                    return Json(new { success = false, message = "提交数据不能为空" });
                }

                // 输出调试信息
                Console.WriteLine($"接收到的数据: Id={model.Id}, PendingtasksNum={model.PendingtasksNum}, PassesNum={model.PassesNum}, NoPassesNum={model.NoPassesNum}");

                // 查找现有记录
                var task = await _dbContext.Set<Pendingtasks>().FindAsync(model.Id);
                if (task == null)
                {
                    // 如果记录不存在，则创建新记录
                    model.DocumentsCode = model.DocumentsCode ?? "";
                    model.DocumentsName = model.DocumentsName ?? "";
                    model.DocumentsType = model.DocumentsType ?? "";
                    model.TicketsCode = model.TicketsCode ?? "";
                    model.TicketsName = model.TicketsName ?? "";
                    model.WorkstationCode = model.WorkstationCode ?? "";
                    model.MaterialCode = model.MaterialCode ?? "";
                    model.MaterialName = model.MaterialName ?? "";
                    
                    // 确保数值字段有正确的值
                    if (model.PendingtasksNum <= 0)
                    {
                        return Json(new { success = false, message = "待检验数量必须大于0" });
                    }
                    
                    await _dbContext.Set<Pendingtasks>().AddAsync(model);
                }
                else
                {
                    // 更新现有记录
                    task.DocumentsCode = model.DocumentsCode ?? task.DocumentsCode;
                    task.DocumentsName = model.DocumentsName ?? task.DocumentsName;
                    task.DocumentsType = model.DocumentsType ?? task.DocumentsType;
                    task.TicketsCode = model.TicketsCode ?? task.TicketsCode;
                    task.TicketsName = model.TicketsName ?? task.TicketsName;
                    task.WorkstationCode = model.WorkstationCode ?? task.WorkstationCode;
                    task.MaterialCode = model.MaterialCode ?? task.MaterialCode;
                    task.MaterialName = model.MaterialName ?? task.MaterialName;
                    
                    // 更新检验结果相关字段
                    if (model.PendingtasksNum > 0)
                    {
                        task.PendingtasksNum = model.PendingtasksNum;
                    }
                    else
                    {
                        return Json(new { success = false, message = "待检验数量必须大于0" });
                    }
                    
                    task.PassesNum = model.PassesNum;
                    task.NoPassesNum = model.NoPassesNum;
                    
                    // 确保PendingtasksNum字段有值
                    if (task.PendingtasksNum <= 0)
                    {
                        task.PendingtasksNum = task.PassesNum + task.NoPassesNum;
                    }
                    
                    Console.WriteLine($"更新后的数据: PendingtasksNum={task.PendingtasksNum}, PassesNum={task.PassesNum}, NoPassesNum={task.NoPassesNum}");
                }

                await _dbContext.SaveChangesAsync();
                
                return Json(new { success = true, message = "保存成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = "保存失败：" + ex.Message });
            }
        }
    }
}
